<!-- eslint-disable vue/valid-v-slot -->
<template>
  <el-form>
    <el-row>
      <el-col :span="12">
        <el-radio-group v-model="tabPosition">
          <el-radio-button
            v-if="queryParams.action === 'examine' && queryParams.type === '1'"
            value="2"
          >
            {{ examineName() }}
          </el-radio-button>
          <el-radio-button value="0">对账单详情</el-radio-button>
          <el-radio-button
            v-if="queryParams.action === 'view'"
            value="1"
            @click="getExamineTableData()"
            >审批记录</el-radio-button
          >
          <el-radio-button
            v-if="queryParams.action === 'examine' && queryParams.type !== '1'"
            value="2"
          >
            {{ examineName() }}
          </el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" style="text-align: right">
        <el-button
          v-if="queryParams.action === 'add' || queryParams.action === 'edit'"
          color="#1E3485"
          @click="submitForm(pjctReconRef)"
          >保存</el-button
        >
        <el-button
          v-if="queryParams.action === 'add' || queryParams.action === 'edit'"
          style="display: none"
          color="#1E3485"
          @click="saveOrSubmit(pjctReconRef)"
          >保存并提交</el-button
        >
        <closeTagButton id="closeTagButtonRef" />
      </el-col>
    </el-row>
    <!-- 对账单详情 -->
    <div v-if="tabPosition === '0'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>基本信息</template>
        <el-form
          ref="pjctReconRef"
          label-width="180px"
          :model="pjctReconModel"
          :rules="rules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="采购合同" required prop="contractName">
                <el-input
                  v-model="pjctReconModel.contractName"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                  @click="showContractSelectDialog"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对账周期" required prop="reconciliationDate">
                <el-date-picker
                  v-model="pjctReconModel.reconciliationDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始"
                  end-placeholder="结束"
                  value-format="YYYY-MM-DD"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="历史对账金额" prop="reconciliationDate">
                <el-input v-model="pjctReconModel.historyTotalPrice" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购单位">
                <el-input v-model="pjctReconModel.purchaseDeptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称">
                <el-input v-model="pjctReconModel.projectName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目所属单位">
                <el-input v-model="pjctReconModel.projectDeptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商">
                <el-input v-model="pjctReconModel.supplierDeptName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- TODO -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="返利点（%）">
                <el-input
                  v-model="pjctReconModel.contractRebatePoints"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同返利额（元）">
                <el-input
                  v-model="pjctReconModel.contractRebatePrice"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  v-model="pjctReconModel.mark"
                  type="textarea"
                  :rows="1"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="供货清单">
                <el-button
                  color="#1E3485"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                  @click="showposupplyListSelectDialog"
                  >选择供货清单</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="acceptanceTableData"
          :loading="acceptanceTableLoading"
          size="mini"
          style="margin-left: 180px"
        >
          <vxe-column type="seq" title="序号" min-width="50" align="center" />
          <vxe-column
            v-for="column in acceptanceTableColumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :align="column.align"
            :min-width="column.width"
            show-overflow
          >
            <template v-slot:default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
          <vxe-column title="操作" min-width="100" align="center" fixed="right">
            <template v-slot:default="{ row }">
              <vxe-button
                type="text"
                size="small"
                @click="
                  toDetail(
                    { id: row.supplyId, title: row.orderName, action: 'view' },
                    'viewSupplyList'
                  )
                "
                >查看</vxe-button
              >
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <span>对账信息</span>
          <el-button
            v-if="queryParams.action != 'add'"
            style="float: right"
            color="#1E3485"
            @click="showFilePreview()"
            >预览/下载</el-button
          >
        </template>
        <vxe-table
          border
          show-footer
          min-height="300"
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="rconMaterialTableData"
          :loading="rconMaterialTableLoading"
          :footer-data="rconMaterialTableFooterData"
          size="mini"
        >
          <vxe-column
            type="seq"
            title="序号"
            width="50"
            fixed="left"
            align="center"
          />
          <vxe-column
            v-for="column in rconMaterialTableCloumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :min-width="column.width"
            :align="column.align"
            show-overflow
          >
            <template
              v-if="
                column.field === 'supplyNum' &&
                (queryParams.action === 'add' || queryParams.action === 'edit')
              "
              v-slot:default="{ row }"
            >
              <vxe-input v-model="row.supplyNum" type="number" :min="0" />
            </template>
            <template v-slot:default="{ row }">
              <div>{{ row[column.field] }}</div>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 核对记录 </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="checkTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="核对人" field="cnName" />
          <vxe-column title="核对时间" field="createdAt" />
          <vxe-column title="实时含税总价（元）" field="bizPrice" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="核对说明" field="mark" />
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 对账确认记录（项目部） </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="reconciliationConfirmTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="确认时间" field="createdAt" />
          <vxe-column title="确认人" field="cnName" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="确认说明" field="mark" />
          <!-- <vxe-column title="状态" field="status">
            <template v-slot:default="{ row }">
              <span v-if="row.status == 4">驳回</span>
              <span v-else-if="row.status == 5">通过</span>
              <span v-else>{{ row.status }}</span>
            </template>
          </vxe-column> -->
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 对账确认记录（云采） </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="ycConfirmTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="确认时间" field="createdAt" />
          <vxe-column title="确认人" field="cnName" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="确认说明" field="mark" />
        </vxe-table>
      </el-card>
    </div>
    <!-- 审批记录 -->
    <div v-if="tabPosition === '1'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>审批记录</template>
        <!-- <div class="examine">
          <img src="@/assets/img/reconciliation.png" alt="" />
        </div> -->
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="examineTableData"
          :loading="examineTableLoding"
          size="mini"
          style="margin-top: 1%"
        >
          <vxe-column title="序号" width="50" align="center" type="seq" />
          <vxe-column
            v-for="column in examineTableColumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :min-width="column.width"
            :align="column.align"
            show-overflow
          >
            <template v-slot:default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
          <vxe-column title="审批附件" field="attachList">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.attachList)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
    </div>
    <!-- 核对确认 -->
    <div v-if="tabPosition === '2'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          {{ examineName() }}
        </template>
        <el-form label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="queryParams.type != '0'" label="对账">
                <el-radio-group v-model="confirmModel.reconStatus">
                  <el-radio value="0">对账确认</el-radio>
                  <el-radio value="1">对账驳回</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="确认时间">
                <el-date-picker
                  v-model="confirmModel.reconDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="确认人">
                <el-input v-model="confirmModel.reconPerson" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="确认说明">
                <el-input v-model="confirmModel.reconRemark" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对账预览下载">
                <el-button
                  color="#1E3485"
                  size="small"
                  @click="showFilePreview()"
                  >预览/下载</el-button
                >
                <span>（注：请下载对账单盖章上传）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="上传附件">
                <el-upload
                  v-model:file-list="fileList"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  multiple
                  style="width: 80%"
                >
                  <el-button :icon="Upload" color="#1E3485" size="small"
                    >点击上传</el-button
                  >
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" style="text-align: center">
              <el-button color="#1E3485" @click="reconConfirmSubmit()"
                >确认</el-button
              >
              <closeTagButton id="closeTagButtonRef" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <div class="dialogs">
      <procureContractSelectDialog
        :visible="contractSelectDialogVisible"
        @close="closeContractSelectDialog"
        @confirm="contractSelectConfirm"
      />
      <posupplyListSelectDialog
        :visible="posupplyListSelectDialogVisible"
        :contractId="pjctReconModel.contractId"
        :idList="acceptanceTableData"
        @close="closeposupplyListSelectDialog"
        @confirm="posupplyListSelectConfirm"
      />
      <filePreview
        :visible="filePreviewVisible"
        :fileId="fileId"
        :fileType="fileType"
        :fileUrl="fileUrl"
        @close="closeFilePreview"
      />
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import type {
  FormInstance,
  UploadUserFile,
  UploadProps,
  UploadFile
} from "element-plus";
import { VxeTablePropTypes } from "vxe-table";
import closeTagButton from "@/components/closeTagButton.vue";
import procureContractSelectDialog from "./dialog/procureContractSelectDialog.vue";
import posupplyListSelectDialog from "./dialog/posupplyListSelectDialog.vue";
import filePreview from "@/components/filePreview.vue";
import { useDetail } from "@/views/ERP_SupplyManage/ERP_SupplyList/components/utils/hooks";
import { useNav } from "@/layout/hooks/useNav";
import { headers, uploadUrl } from "@/api/utils";
import {
  getSupplierRecoMaterialDataList,
  saveSupplierRecoData,
  getSupplierRecoDataInfo,
  getReconciliationPosupplyDataList,
  getSupReconciliationMaterialDataList,
  getSupReconciliationMaterialDataListFooter,
  getConfirmHistoryList,
  spReconciliationCheck,
  spReconciliationConfirm,
  spReconciliationYcConfirm,
  sprecoSubmitAudit,
  getSupplySettlementSum
} from "@/api/ERP_settlement";
import { getAuditHistoryTaskList } from "@/api/ERP_public";
import { ElLoading } from "element-plus";

///////////////////////// 公共 /////////////////////////
// 路由跳转
const { toDetail, router } = useDetail();
const route = useRoute();
const queryParams = route.query;
let examineName = () => {
  switch (queryParams.type) {
    case "0":
      return "核对确认";
    case "1":
      return "对账确认";
    case "2":
      return "云采确认";
  }
};
// 当前登录用户名
const { username } = useNav();
///////////////////////// 数据准备 /////////////////////////
// 默认显示页
let tabPosition = ref("0");
// 详情表单数据
const pjctReconRef = ref<FormInstance>();
let pjctReconModel = reactive({
  id: "", // 对账ID
  contractId: "", // 合同ID
  contractNo: "", // 合同编号
  contractName: "", // 合同名称
  saleContractId: "", // 销售合同ID
  reconciliationDate: [], // 对账周期
  purchaseDeptName: "", // 采购单位名称
  projectName: "", // 项目名称
  projectDeptName: "", // 供货单位名称
  supplierDeptName: "", // 供应商名称
  contractRebatePoints: "", // 返利点（%）
  contractRebatePrice: "", // 合同返利额（元）
  mark: "", // 备注
  processInstanceId: "", // 审核记录ID
  historyTotalPrice: "" //历史对账金额
});
// 供货清单表
let acceptanceTableData = ref([]);
let acceptanceTableLoading = ref(false);
const acceptanceTableColumns = reactive([
  {
    field: "orderSn",
    title: "订单编号",
    width: 150,
    align: "left"
  },
  {
    field: "orderName",
    title: "订单名称",
    width: 150,
    align: "left"
  },
  {
    field: "taxTotalPrice",
    title: "含税总价（元）",
    width: 150,
    align: "right"
  },
  {
    field: "shipmentAt",
    title: "供货时间",
    width: 150,
    align: "center"
  },
  {
    field: "takeAt",
    title: "验收时间",
    width: 150,
    align: "center"
  }
]);
// 对账信息表
let rconMaterialTableData = ref([]);
let rconMaterialTableFooterData = ref<VxeTablePropTypes.FooterData>([]);
let rconMaterialTableLoading = ref(false);
const rconMaterialTableCloumns = reactive([
  {
    field: "orderSn",
    title: "订单编号",
    width: 150,
    align: "center"
  },
  {
    field: "materialCode",
    title: "材料编码",
    width: 150,
    align: "center"
  },
  {
    field: "materialName",
    title: "材料名称",
    width: 150,
    align: "center"
  },
  {
    field: "materialSpecs",
    title: "规格",
    width: 150,
    align: "center"
  },
  {
    field: "materialModel",
    title: "型号",
    width: 150,
    align: "center"
  },
  {
    field: "materialUnit",
    title: "单位",
    width: 150,
    align: "center"
  },
  {
    field: "materialBrand",
    title: "品牌",
    width: 150,
    align: "center"
  },
  {
    field: "supplyNum",
    title: "供货数量",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "comfirmSupplyNum",
    title: "确认数量",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "excludingTaxUnitPrice",
    title: "不含税单价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "includingTaxUnitPrice",
    title: "含税单价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "tax",
    title: "税率（%）",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "includingTaxTotalPrice",
    title: "含税总价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "reconciliationPrice",
    title: "确认含税总价（元）",
    width: 150,
    align: "right",
    fixed: "right"
  },
  {
    field: "materialMark",
    title: "备注",
    width: 120,
    align: "center",
    fixed: "right"
  }
]);
// 详情表单校验
const rules = reactive({
  contractName: [
    { required: true, message: "请选择采购合同", trigger: "blur" }
  ],
  reconciliationDate: [
    { required: true, message: "请选择对账周期", trigger: "blur" }
  ]
});
// 核对/确认表格
let checkTableData = ref([]);
let reconciliationConfirmTableData = ref([]);
let ycConfirmTableData = ref([]);
// 审核记录表格
let examineTableData = ref([]);
let examineTableLoding = ref(false);
const examineTableColumns = reactive([
  {
    field: "actName",
    title: "流程节点",
    width: 100,
    align: "center"
  },
  {
    field: "auditDate",
    title: "审批时间",
    width: 100,
    align: "center"
  },
  {
    field: "auditUserName",
    title: "审批人",
    width: 100,
    align: "center"
  },
  {
    field: "auditResultMsg",
    title: "审批结果",
    width: 100,
    align: "center"
  },
  {
    field: "auditMessage",
    title: "审批意见",
    width: 100,
    align: "center"
  }
]);
// 确认表单数据
let confirmModel = reactive({
  reconStatus: "0", // 确认状态
  reconDate: new Date().toISOString().slice(0, 10), // 确认时间
  reconPerson: username.value, // 确认人
  reconRemark: "", // 确认说明
  reconFile: "" // 确认附件
});
///////////////////////// 弹窗类 /////////////////////////
// 选择合同弹窗
let contractSelectDialogVisible = ref(false);
function showContractSelectDialog() {
  contractSelectDialogVisible.value = true;
}
function closeContractSelectDialog(val: boolean) {
  contractSelectDialogVisible.value = val;
}
const contractSelectConfirm = data => {
  pjctReconModel.contractId = data.contractId;
  pjctReconModel.contractNo = data.contractNo;
  pjctReconModel.contractName = data.contractName;
  pjctReconModel.saleContractId = data.saleContractId;
  pjctReconModel.projectName = data.projectName;
  pjctReconModel.purchaseDeptName = data.purchaseDeptName;
  pjctReconModel.projectDeptName = data.projectDeptName;
  pjctReconModel.supplierDeptName = data.supplierDeptName;
  pjctReconModel.contractRebatePoints = data.contractRebatePoints;
  pjctReconModel.contractRebatePrice = data.contractRebatePrice;
  acceptanceTableData.value = [];
  rconMaterialTableData.value = [];
};
// 供货清单弹窗
let posupplyListSelectDialogVisible = ref(false);
function showposupplyListSelectDialog() {
  if (pjctReconModel.contractName === "") {
    ElMessage.error("请先选择采购合同！");
  } else {
    posupplyListSelectDialogVisible.value = true;
  }
}
function closeposupplyListSelectDialog(val: boolean) {
  posupplyListSelectDialogVisible.value = val;
}
const posupplyListSelectConfirm = data => {
  for (let i = 0; i < data.selectedRow.length; i++) {
    const exists = acceptanceTableData.value.some(
      item => item.id === data.selectedRow[i].id
    );
    if (exists) {
      ElMessage.error("该数据已存在");
    } else {
      acceptanceTableData.value.push({
        supplyId: data.selectedRow[i].id,
        ...data.selectedRow[i]
      });
    }
  }
  getAcceptanceTableDataList();
};
// 预览/下载 弹窗
let filePreviewVisible = ref(false);
let fileId = ref("");
let fileType = ref("");
let fileUrl = ref("");
function showFilePreview() {
  fileId.value = queryParams.id as string;
  fileType.value = "ordrecon";
  filePreviewVisible.value = true;
}
function closeFilePreview(val: boolean) {
  filePreviewVisible.value = val;
}
// 上传按钮&相关事件
let fileList = ref<UploadUserFile[]>([]);
let reconFileList: any = [];
const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};
// 文件上传成功,传参赋值，格式修改
const handleSuccess = (fileList: any) => {
  reconFileList.push(fileList.data);
  const formatterObj = [];
  for (let i in reconFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = reconFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      reconFileList[i].name.substring(
        reconFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = reconFileList[i].name;
    formatterObj.push(tempvalue);
  }
  confirmModel.reconFile = JSON.stringify(formatterObj);
};
const beforeRemove = (uploadFile: UploadFile) => {
  let fileItems = JSON.parse(confirmModel.reconFile);
  fileItems.forEach((item, index) => {
    if (item.fileOriginName == uploadFile.name) {
      fileItems.splice(index, 1);
    }
  });
  confirmModel.reconFile = fileItems;
  return true;
};
// 表格附件预览
function downloadFile(fileUrl) {
  window.open(fileUrl, "_blank");
}
///////////////////////// 数据请求 /////////////////////////
// 获取供货清单绑定的材料列表
async function getAcceptanceTableDataList() {
  rconMaterialTableLoading.value = true;
  let params: ApiParams = {};
  params.idList = acceptanceTableData.value.map(item => item.id);
  try {
    const response: ApiResponse = await getSupplierRecoMaterialDataList(params);
    if (response.code === 200) {
      rconMaterialTableData.value = response.data.records;
      getTaxTotalPrice();
    } else {
      ElMessage.error("获取此部分供货清单绑定的材料列表失败");
    }
  } catch (error) {
  } finally {
    rconMaterialTableLoading.value = false;
  }
}
// 新增/编辑 - 提交表单
async function submitForm(formEl: FormInstance | undefined) {
  // 表单校验
  if (!formEl) return;
  try {
    const valid = await formEl.validate();
    if (!valid) {
      return false;
    }
  } catch (error) {
    ElMessage.error("输入有误，请检查！");
    return false;
  }
  let params: ApiParams = {
    poSupplyIdList: []
  };
  if (queryParams.id && queryParams.id !== "") {
    params.id = queryParams.id;
    params.historyTotalPrice = pjctReconModel.historyTotalPrice;
  }
  params.contractMethod = 1;
  params.contractId = pjctReconModel.contractId;
  params.contractNo = pjctReconModel.contractNo;
  params.contractName = pjctReconModel.contractName;
  params.projectName = pjctReconModel.projectName;
  params.reconciliationStartDate = pjctReconModel.reconciliationDate[0];
  params.reconciliationEndDate = pjctReconModel.reconciliationDate[1];
  params.purchaseDeptName = pjctReconModel.purchaseDeptName;
  params.projectDeptName = pjctReconModel.projectDeptName;
  params.supplierDeptName = pjctReconModel.supplierDeptName;
  params.contractRebatePoints = pjctReconModel.contractRebatePoints;
  params.contractRebatePrice = pjctReconModel.contractRebatePrice;
  params.mark = pjctReconModel.mark;
  for (let i = 0; i < acceptanceTableData.value.length; i++) {
    params.poSupplyIdList.push(acceptanceTableData.value[i].supplyId);
  }
  params.spReconciliationMaterialList = rconMaterialTableData.value;
  // for (let i = 0; i < rconMaterialTableData.value.length; i++) {
  //   params.poSupplyIdList.push(rconMaterialTableData.value[i].supplyId);
  // }
  try {
    const response: ApiResponse = await saveSupplierRecoData(params);
    if (response.code === 200) {
      ElMessage.success("提交成功");
      document.getElementById("closeTagButtonRef").click();
    } else {
      ElMessage.error("提交失败");
    }
  } catch (error) {}
}
// 核对确认
async function reconConfirmSubmit() {
  let params: ApiParams = {};
  params.id = queryParams.id;
  // 核对确认
  if (queryParams.type === "0") {
    params.reconciliationConfirmDate = confirmModel.reconDate;
    params.reconciliationConfirmPerson = confirmModel.reconPerson;
    params.reconciliationConfirmMark = confirmModel.reconRemark;
    params.reconciliationFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await spReconciliationCheck(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
  // 对账确认
  if (queryParams.type === "1") {
    params.reconciliationConfirmStatus =
      confirmModel.reconStatus === "0" ? true : false;
    params.reconciliationConfirmDate = confirmModel.reconDate;
    params.reconciliationConfirmPerson = confirmModel.reconPerson;
    params.reconciliationConfirmMark = confirmModel.reconRemark;
    params.reconciliationFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await spReconciliationConfirm(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
  // 云采确认
  if (queryParams.type === "2") {
    params.reconciliationConfirmStatus =
      confirmModel.reconStatus === "0" ? true : false;
    params.reconciliationConfirmDate = confirmModel.reconDate;
    params.reconciliationConfirmPerson = confirmModel.reconPerson;
    params.reconciliationConfirmMark = confirmModel.reconRemark;
    params.reconciliationFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await spReconciliationYcConfirm(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
}
// 获取对账单详情
async function getReconciliationDetail() {
  let params: ApiParams = {};
  params.id = queryParams.id;
  params.contractMethod = 1;
  try {
    const response: ApiResponse = await getSupplierRecoDataInfo(params);
    if (response.code === 200) {
      // 表单部分
      pjctReconModel.id = response.data.id;
      pjctReconModel.contractId = response.data.contractId;
      pjctReconModel.contractNo = response.data.contractNo;
      pjctReconModel.contractName = response.data.contractName;
      pjctReconModel.projectName = response.data.projectName;
      pjctReconModel.reconciliationDate = [
        response.data.reconciliationStartDate,
        response.data.reconciliationEndDate
      ];
      pjctReconModel.purchaseDeptName = response.data.purchaseDeptName;
      pjctReconModel.projectDeptName = response.data.projectDeptName;
      pjctReconModel.supplierDeptName = response.data.supplierDeptName;
      pjctReconModel.contractRebatePoints = response.data.contractRebatePoints;
      pjctReconModel.contractRebatePrice = response.data.contractRebatePrice;
      pjctReconModel.mark = response.data.mark;
      pjctReconModel.processInstanceId = response.data.processInstanceId;
      pjctReconModel.historyTotalPrice = response.data.historyTotalPrice;
    } else {
      ElMessage.error("获取对账单详情失败: " + response.msg);
    }
  } catch (error) {}
}
// 获取核对表记录
async function getConfirmTablesData(type: string) {
  let params: ApiParams = {};
  params.bizId = queryParams.id;
  params.type = type;
  // 核对确认表
  if (type === "0") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    checkTableData.value = response.data;
  }
  // 对账确认表
  if (type === "1") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    reconciliationConfirmTableData.value = response.data;
  }
  // 云采确认表
  if (type === "3") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    ycConfirmTableData.value = response.data;
  }
}
// 获取绑定的供货清单
async function getReconciliationOrderList() {
  acceptanceTableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = 1;
  params.pageSize = 999;
  params.reconciliationId = queryParams.id;
  try {
    const response: ApiResponse =
      await getReconciliationPosupplyDataList(params);
    if (response.code === 200) {
      acceptanceTableData.value = response.data.records;
    } else {
      ElMessage.error("获取绑定的供货清单失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    acceptanceTableLoading.value = false;
  }
}
// 获取绑定的材料列表
async function getReconciliationMaterialList() {
  rconMaterialTableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = 1;
  params.pageSize = 999;
  params.reconciliationId = queryParams.id;
  try {
    const response: ApiResponse =
      await getSupReconciliationMaterialDataList(params);
    if (response.code === 200) {
      rconMaterialTableData.value = response.data.records;
      if (rconMaterialTableData.value.length != 0) {
        getAcceptanceTableDataListFooter();
      }
    } else {
      ElMessage.error("获取材料列表失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    rconMaterialTableLoading.value = false;
  }
}
// 获取绑定的材料列表footer数据
async function getAcceptanceTableDataListFooter() {
  let params: ApiParams = {};
  params.id = queryParams.id;
  const response: ApiResponse =
    await getSupReconciliationMaterialDataListFooter(params);
  if (response.code === 200 && response.data) {
    rconMaterialTableFooterData.value = [];
    rconMaterialTableFooterData.value.push({
      supplyNum: response.data.countSupplyNum,
      comfirmSupplyNum: response.data.countComfirmSupplyNum,
      includingTaxTotalPrice: response.data.countIncludingTaxtotalPrice,
      reconciliationPrice: response.data.countReconciliationPrice
    });
  } else {
    ElMessage.error("获取材料列表页脚数据失败: " + response.msg);
  }
}
// 获取审批记录
async function getExamineTableData() {
  examineTableLoding.value = true;
  let params: ApiParams = {};
  params.processInstanceId = pjctReconModel.processInstanceId;
  try {
    const response: ApiResponse = await getAuditHistoryTaskList(params);
    if (response.code === 200) {
      examineTableData.value = response.data;
    } else {
      ElMessage.error("获取审批记录失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    examineTableLoding.value = false;
  }
}
///保存并提交
async function saveOrSubmit(formEl: FormInstance | undefined) {
  // 表单校验
  if (!formEl) return;
  try {
    const valid = await formEl.validate();
    if (!valid) {
      return false;
    }
  } catch (error) {
    ElMessage.error("输入有误，请检查！");
    return false;
  }
  let params: ApiParams = {
    poSupplyIdList: []
  };
  if (queryParams.id && queryParams.id !== "") {
    params.id = queryParams.id;
    params.historyTotalPrice = pjctReconModel.historyTotalPrice;
  }
  params.contractMethod = 1;
  params.contractId = pjctReconModel.contractId;
  params.contractNo = pjctReconModel.contractNo;
  params.contractName = pjctReconModel.contractName;
  params.projectName = pjctReconModel.projectName;
  params.reconciliationStartDate = pjctReconModel.reconciliationDate[0];
  params.reconciliationEndDate = pjctReconModel.reconciliationDate[1];
  params.purchaseDeptName = pjctReconModel.purchaseDeptName;
  params.projectDeptName = pjctReconModel.projectDeptName;
  params.supplierDeptName = pjctReconModel.supplierDeptName;
  params.contractRebatePoints = pjctReconModel.contractRebatePoints;
  params.contractRebatePrice = pjctReconModel.contractRebatePrice;
  params.mark = pjctReconModel.mark;
  for (let i = 0; i < acceptanceTableData.value.length; i++) {
    params.poSupplyIdList.push(acceptanceTableData.value[i].supplyId);
  }
  params.spReconciliationMaterialList = rconMaterialTableData.value;
  try {
    const response: ApiResponse = await saveSupplierRecoData(params);
    let loadingInstance = ElLoading.service({
      lock: true,
      text: "单据提交中",
      background: "rgba(0, 0, 0, 0.7)"
    });
    if (response.code === 200) {
      let param: ApiParams = {};
      param.id = response.data;
      const res: ApiResponse = await sprecoSubmitAudit(param);
      if (res.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
        loadingInstance.close();
      } else {
        ElMessage.error("提交失败：" + res.msg);
        loadingInstance.close();
      }
    } else {
      ElMessage.error("提交失败");
      loadingInstance.close();
    }
  } catch (error) {}
}
async function getTaxTotalPrice() {
  let arr = [];
  for (let i in rconMaterialTableData.value) {
    arr.push(rconMaterialTableData.value[i].id);
  }
  let params: ApiParams = {};
  params.contractId = pjctReconModel.contractId;
  const response: ApiResponse = await getSupplySettlementSum(params);
  if (response.code === 200) {
    pjctReconModel.historyTotalPrice = response.data;
  }
}
///////////////////////// 公共 /////////////////////////
onMounted(async () => {
  if (queryParams.action === "examine") {
    tabPosition.value = "2";
  }
  if (queryParams.action != "add") {
    await getReconciliationDetail();
    await getReconciliationOrderList();
    await getReconciliationMaterialList();
    await getConfirmTablesData("0");
    await getConfirmTablesData("1");
    await getConfirmTablesData("3");
    //getTaxTotalPrice();
  }
});
</script>

<style lang="scss" scoped>
.examine {
  display: grid;
  place-items: center;
  img {
    height: 15vh;
  }
}
</style>
